package client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ThreadEcouteServeurUDP extends Thread {
	private DatagramSocket s;
	
	private FenetreJeu fen;
	private boolean stop;

	public ThreadEcouteServeurUDP(DatagramSocket s,
			FenetreJeu fen) {
		super();
		this.s = s;
		this.fen = fen;
		stop = false;
	}
	
	public void Stopper()
	{
		s.close();
		stop = true;
	}

	public void run() {
		try
		{
			byte[] buf = new byte[256];
			DatagramPacket packet = new DatagramPacket(buf, buf.length);
			while(!stop)
			{
				s.receive(packet);
				String rec = new String(packet.getData());
				System.out.println("UDP recu: "+rec+ "test");
				String[] tab_r = rec.split(":");
				if (tab_r[0].equals("MVT"))
				{
					int id, r, c;
					id = Integer.parseInt(tab_r[1]);
					r = Integer.parseInt(tab_r[2]);
					c = Integer.parseInt(tab_r[3]);
					fen.getJeu().deplacerJoueur(id, r, c);
				}
				else
				if (tab_r[0].equals("NEW"))
				{
					int id, r, c;
					char t;
					String nom;
					id = Integer.parseInt(tab_r[1]);
					nom = tab_r[2];
					t = tab_r[3].charAt(0);
					r = Integer.parseInt(tab_r[4]);
					c = Integer.parseInt(tab_r[5]);
					fen.getJeu().ajouterJoueur(id, t, nom, r, c);
				}
				else
				if (tab_r[0].equals("DEC"))
				{
					int id;
					id = Integer.parseInt(tab_r[1].split("0")[0]);
					fen.getJeu().supprimerJoueur(id);
				}
			}
		}
		catch (IOException e)
		{
			System.out.println(e.toString());
		}
	}
}
